import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:riki_base_flutter/riki_base_flutter.dart';
import 'package:riki_base_flutter/router/fluro_navigator.dart';
import 'package:riki_login/config/config.dart';
import 'package:riki_login/config/global.dart';
import 'package:riki_login/pages/staff/widgets/login_privacy_widget.dart';
import 'package:riki_login/r.dart';
import 'package:riki_login/res/colors.dart';
import 'package:riki_login/res/header.dart';
import 'package:riki_webview/entity/riki_webview_config.dart';
import 'package:riki_webview/event/back_event.dart';
import 'package:riki_webview/event/next_page_event.dart';
import 'package:riki_webview/riki_webview.dart';

import 'package:wangyi_yidun_flutter_plugin/wangyi_yidun_flutter_plugin.dart';

import '../../riki_login.dart';
import 'staff_login_code_viewmodel.dart';
import 'widgets/login_common_widget.dart';

///作者：范玉辉
///创建时间：2020/12/15
///说明：APP2.0验证码登录

class StaffLoginCodePage extends StatefulWidget {
  @override
  _StaffLoginCodePageState createState() => _StaffLoginCodePageState();
}

class _StaffLoginCodePageState extends BaseScaffoldState<StaffLoginCodePage> {
  var eventChannel = const EventChannel("yd_captcha_flutter_event_channel");
  late StaffLoginCodeViewModel viewModel;
  TextEditingController _userPhoneController = TextEditingController();
  TextEditingController _userCodeController = TextEditingController();
  //表单状态
  GlobalKey _formKey = GlobalKey();
  bool _isShowClear = false; //是否显示输入框尾部的清除按钮
  bool isAgreement = RikiLogin.instance.isAgreement;
  // 是否按下登录
  bool isTapDown = false;
  // 是否可以点击登录
  bool isTap = false;
  // 是否按下获取验证码
  bool isTapSendCode = false;

  StreamSubscription? _streamSubscription;

  List<BoxShadow> cardShadow = [
    BoxShadow(
        offset: Offset(0, 6),
        color: RikiLoginColors.cardShadowColor,
        blurRadius: 14.w, //阴影模糊程度
        spreadRadius: -6.w //阴影扩散程度
        ),
  ];

  // 验证手机号
  String? validateUserName(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(r'^(13|14|15|16|17|18|19)\d{9}$');
    if (!exp.hasMatch(value)) {
      return '手机号格式错误!';
    }
    return null;
  }

  @override
  void initState() {
    // 网易滑块回调
    eventChannel.receiveBroadcastStream().listen(_onData, onError: _onError);
    _streamSubscription = RikiApplication.eventBus.on().listen(_handleEvent);

    //监听手机号框的输入改变
    _userPhoneController.addListener(() {
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPhoneController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    // 验证码输入监听
    _userCodeController.addListener(() {
      if (_userCodeController.text.length > 0) {
        isTap = true;
      } else {
        isTap = false;
      }
      setState(() {});
    });
    super.initState();
  }

  /// EventBux事件处理
  void _handleEvent(event) async {
    try {
      if (event is NextPageEvent) {
        if (event.title == null) {
          RikiWebView.instance.enter(
            context,
            RikiWebViewConfig(
              getWebUrlWithEvent(event),
              statusBar: false,
              isDarkTheme: event.isDarkTheme,
              userAgent: RikiLoginAppConfig.user_agent,
            ),
          );
        } else {
          RikiWebView.instance.enter(
            context,
            RikiWebViewConfig(
              getWebUrlWithEvent(event),
              isDarkTheme: event.isDarkTheme,
              userAgent: RikiLoginAppConfig.user_agent,
            ),
          );
        }
      } else if (event is BackEvent) {
        NavigatorUtils.goBack(context);
      }
    } catch (e) {
      LogUtil.v(e.toString());
    }
  }

  String getWebUrlWithEvent(NextPageEvent event) {
    String token = RikiLoginGlobal.isLoginUserAccount() ? (RikiLoginGlobal.getLocalUserAccount()?.accessToken ?? '') : '';
    String url = event.webUrl ?? '';
    if (!url.contains('http')) {
      url = RikiLogin().h5Url + url;
    }
    if (event.token) {
      url = url + '&token=$token';
    }
    LogUtil.v('打印一下URL' + url);
    return url;
  }

  /// 网易验证成功
  void _onData(response) {
    var validate = (response as Map)['validate'];
    if (validate != null && !validate.isEmpty) {
      print(validate);
      //发送验证码
      getLoginCode(validate);
    }
  }

  /// 网易验证出现错误
  void _onError(Object error) {
    ToastUtil.showNegativeToast('加载验证码出现错误');
  }

  @override
  bool resizeToAvoidBottomInset() {
    return false;
  }

  isPageObserver() {
    return true;
  }

  @override
  void didPopNext() {
    super.didPopNext();
    setState(() {
      this.isAgreement = RikiLogin.instance.isAgreement;
    });
  }

  @override
  Widget buildBody(BuildContext context) {
    return ProviderWidget<StaffLoginCodeViewModel>(
      builder: (context, model, child) {
        return buildBodyWidget();
      },
      model: StaffLoginCodeViewModel(),
      onModelReady: (model) {
        viewModel = model;
        viewModel.initApi(context);
      },
      pageStatusFactory: null,
    );
  }

  @override
  Widget buildAppBar(BuildContext context) {
    return RikiAppBar(
      isBack: false,
    );
  }

  Widget buildBodyWidget() {
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Container(
        width: 375.w,
        color: RikiLoginColors.app_white,
        child: Stack(
          alignment: Alignment.center,
          children: [
            // 账号和验证码内容
            containWidget(),
            // 底部功能区域
            bottomWidget(),
          ],
        ),
      ),
    );
  }

  /// 账号和验证码内容
  Widget containWidget() {
    return Container(
      margin: EdgeInsets.only(top: 20.w, left: 37.5.w, right: 37.5.w),
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            buildRowText('欢迎登录打扮家'),
            Container(
              padding: EdgeInsets.only(top: 37.w),
              child: TextFormField(
                controller: _userPhoneController,
                // focusNode: _focusNodeUserPhone,
                // autofocus: true,
                //光标颜色
                cursorColor: RikiLoginColors.app_main,
                cursorWidth: 2,
                keyboardType: TextInputType.number,
                //设置键盘类型,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: "请输入手机号",
                  hintStyle: TextStyle(
                    color: RikiLoginColors.text_999999,
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: RikiLoginColors.app_transparent, //输入框底边线
                    ),
                  ),
                  //尾部添加清除按钮
                  suffixIcon: (_isShowClear)
                      ? GestureDetector(
                          onTap: () {
                            // 清空输入框内容
                            _userPhoneController.clear();
                            viewModel.userPhone = '';
                          },
                          child: Container(
                            padding: EdgeInsets.only(left: 20.w),
                            child: ImageUtil.loadAssetImage(R.libAssetsIcLoginInputClear, width: 24.w, height: 24.w,package: RikiLogin.PACKAGE),
                          ),
                        )
                      : Empty.ui,
                ),
                inputFormatters: <TextInputFormatter>[
                  FilteringTextInputFormatter.digitsOnly, //只输入数字
                  LengthLimitingTextInputFormatter(11) //限制长度
                ],
                //验证手机号
                validator: validateUserName,
                //保存数据
                onChanged: (String value) {
                  viewModel.userPhone = value;
                },
              ),
            ),
            Container(
              color: Color.fromRGBO(153, 153, 153, 0.3),
              height: 1,
            ),
            Row(
              children: [
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(top: 30.w),
                    child: TextFormField(
                      controller: _userCodeController,
                      // focusNode: _focusNodeUserPhone,
                      // autofocus: true,
                      //光标颜色
                      cursorColor: RikiLoginColors.app_main,
                      cursorWidth: 2,
                      keyboardType: TextInputType.number,
                      //设置键盘类型
                      decoration: InputDecoration(
                        hintText: "请输入验证码",
                        hintStyle: TextStyle(
                          color: RikiLoginColors.text_999999,
                        ),
                        border: InputBorder.none,
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: RikiLoginColors.app_white, //输入框底边线
                          ),
                        ),
                      ),

                      inputFormatters: <TextInputFormatter>[
                        FilteringTextInputFormatter.digitsOnly, //只输入数字
                        LengthLimitingTextInputFormatter(6) //限制长度
                      ],
                      //保存数据
                      onChanged: (String value) {
                        viewModel.userCode = value;
                      },
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 30.w),
                  child: Selector(builder: (BuildContext context, int data, Widget? child) {
                    return viewModel.sendCode == '获取验证码'
                        ? GradientBgButton(
                            onTap: () {
                              showCaptcha();
                            },
                            enabled: viewModel.userPhone.length == 11,
                            width: 75.w,
                            height: 25.w,
                            title: viewModel.sendCode,
                            fontSize: 11.sp,
                          )
                        : GestureDetector(
                            onTap: () {
                              if (viewModel.sendCode == '重发') {
                                showCaptcha();
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerRight,
                              width: 75.w,
                              height: 25.w,
                              child: Selector(builder: (BuildContext context, int data, Widget? child) {
                                return Text(
                                  viewModel.sendCode,
                                  style: viewModel.sendCode == '重发' ? _textMediumStyle : _textRegularStyle,
                                );
                              }, selector: (BuildContext context, StaffLoginCodeViewModel counterProvider) {
                                return counterProvider.countdownTime;
                              }),
                            ),
                          );
                  }, selector: (BuildContext context, StaffLoginCodeViewModel counterProvider) {
                    return counterProvider.countdownTime;
                  }),
                ),
              ],
            ),
            Container(
              color: Color.fromRGBO(153, 153, 153, 0.3),
              height: 1,
            ),
            45.vGap,
            Container(
              decoration: BoxDecoration(
                boxShadow: (viewModel.userPhone.length == 11 && viewModel.userCode.length > 0) ? cardShadow : null,
              ),
              child: GradientBgButton(
                onTap: () {
                  loginClick();
                },
                enabled: (viewModel.userPhone.length == 11 && viewModel.userCode.length > 0),
                width: 300.w,
                height: 44.w,
                title: "登录",
                fontSize: 16.sp,
              ),
            ),
            LoginPrivacyWidget(this.isAgreement, (isAgreement) {
              if (mounted)
                setState(() {
                  this.isAgreement = isAgreement;
                });
            }),
          ],
        ),
      ),
    );
  }

  Widget bottomWidget() {
    return Positioned(
      bottom: MediaQuery.of(context).padding.bottom,
      right: 0,
      left: 0,
      child: Column(
        children: [
          GestureDetector(
            onTap: () => NavigatorUtils.push(context, RikiLoginRouter.staffLoginPassword).then((value) {
              if (value != null) {
                setState(() {
                  this.isAgreement = value;
                });
              }
            }),
            child: Center(
              child: Column(
                children: <Widget>[
                  ImageUtil.loadAssetImage(R.libAssetsIcLoginCode, width: 40.w, height: 40.w,package: RikiLogin.PACKAGE),
                  6.vGap,
                  Text(
                    '密码登录',
                    style: TextStyle(fontSize: 12.sp, color: RikiLoginColors.text_333333),
                  )
                ],
              ),
            ),
          ),
          25.vGap,
          BuildRegisterWidget(listener: (_) {}),
        ],
      ),
    );
  }

  // 登录
  void loginClick() async {
    if (viewModel.userPhone.length != 11 || viewModel.userCode.length == 0) {
      return;
    }
    if (!this.isAgreement) {
      ToastUtil.show("请勾选服务协议!");
      return;
    }
    if (!validateUserPhone(viewModel.userPhone)) {
      ToastUtil.showNegativeToast("手机号格式错误");
      return;
    }
    showLoading(afterDismiss: () {
      RikiLogin.instance.onLoginSuccessCallback(context);
    });
    viewModel.checkCode().whenComplete(() => hideLoading());
  }

  Future<void> showCaptcha() async {
    if (viewModel.userPhone.length == 0) {
      print(viewModel.userPhone);
      ToastUtil.show('请输入手机号');
      return;
    }
    // 手机号是否填写
    if (viewModel.userPhone.length < 11 && viewModel.userPhone.length > 0) {
      print(viewModel.userPhone);
      ToastUtil.show('手机号错误，请重新输入');
      return;
    }
    if (viewModel.sendCode != '获取验证码' && viewModel.sendCode != '重发') {
      return;
    }
    //协议是否开着
    if (!this.isAgreement) {
      ToastUtil.show("请勾选服务协议!");
      return;
    }
    // 关闭键盘
    FocusScope.of(context).requestFocus(FocusNode());
    WangyiYidunFlutterPlugin.setup(appKey: RikiLogin.instance.netEasyAppKey);
  }

  // 获取验证码
  void getLoginCode(String neCaptchaValidate) async {
    showLoading();
    viewModel.sendSmsCodeFun(neCaptchaValidate).whenComplete(() => hideLoading());
  }

  @override
  void dispose() {
    _streamSubscription?.cancel();
    _streamSubscription = null;
    super.dispose();
  }

  // 验证手机号
  bool validateUserPhone(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(r'^(13|14|15|16|17|18|19)\d{9}$');
    if (!exp.hasMatch(value)) {
      return false;
    }
    return true;
  }

  TextStyle _textMediumStyle = TextStyle(color: RikiLoginColors.app_main, fontSize: 11.sp, fontWeight: FontWeightExt.medium);
  TextStyle _textRegularStyle = TextStyle(color: RikiLoginColors.text_333333, fontSize: 11.sp);
}
